/**
 * Program : ReadFileUtils.java 
 * Author : shadow guo 
 * Create : 2009-11-1 上午01:14:28
 * 
 * Copyright 2008 by Tongfu Information Technology Co. Ltd All rights reserved.
 * 
 * This software is the confidential and proprietary information of Tongfu Information Technology
 * Co. Ltd. ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with
 * Tongfu Information Technology Co. Ltd.
 * 
 */

/**
 * 
 */
package com.tongfusoft.utils.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author shadowguo
 * 
 */
public class ReadFileUtils {
  private final static String encoding = System.getProperties().getProperty("file.encoding");

  /**
   * 
   * 读取文件，返回byte的数组
   * 
   * @param fileName
   * @return byte[]
   * @throws
   */
  public static byte[] readByteFile(String fileName) throws IOException {
    return readByteFile(new File(fileName));
  }

  /**
   * 
   * 读取文件，返回byte的数组
   * 
   * @param file
   * @return byte[]
   * @throws
   */
  public static byte[] readByteFile(File file) throws IOException {
    byte[] result = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    FileInputStream input = new FileInputStream(file);
    int count = 0;
    byte[] b = new byte[1024];

    try {
      while (input.available() > 0) {
        count = input.read(b);
        if (count != -1) {
          out.write(b, 0, count);
        }
      }

      result = out.toByteArray();
    } finally {
      input.close();
      out.close();
    }

    return result;
  }

  /**
   * 
   * 返回字符文件的内容,采用默认的编码格式
   * 
   * @param fileName
   * @return String
   * @throws
   */
  public static String readCharFile(String fileName) throws IOException {
    return readCharFile(new File(fileName));
  }

  /**
   * 
   * 根据设定的编码格式，返回文件内容
   * 
   * @param fileName
   * @param encoding
   * @return String
   * @throws
   */
  public static String readCharFile(String fileName, String encoding)
      throws UnsupportedEncodingException, IOException {
    return readCharFile(new File(fileName), encoding);
  }

  /**
   * 
   * 根据系统的默认编码格式，返回文件内容
   * 
   * @param file
   * @return String
   * @throws
   */
  public static String readCharFile(File file) throws UnsupportedEncodingException, IOException {
    return readCharFile(file, encoding);
  }

  /**
   * 
   * 根据设定的编码格式，返回文件内容
   * 
   * @param file
   * @param encoding
   * @return String
   * @throws
   */
  public static String readCharFile(File file, String encoding)
      throws UnsupportedEncodingException, IOException {
    return new String(readByteFile(file), encoding);
  }
}
